
//463.岛屿的周长
class Solution {
public:
    int islandPerimeter(vector<vector<int>>& grid) {
        int n=grid.size(),m=grid[0].size();
        int ans=0,flag=1;
        int dx[]={0,0,1,-1};
        int dy[]={1,-1,0,0};

        function<int(int ,int)> dfs=[&](int x,int y)
        {
            int ret=0;
            grid[x][y]=-1;
            for(int k=0;k<4;k++)
            {
                int a=x+dx[k];
                int b=y+dy[k];
                if(a<0||a>=n||b<0||b>=m||grid[a][b]==0) ret++;   //旁边是河,周长+1
                else if(a>=0&&a<n&&b>=0&&b<m&&grid[a][b]==1) ret+=dfs(a,b);  //旁边不是河,向旁边扩
            }
            return ret;
        };
        int ret=0;
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<m;j++)
                if(grid[i][j]==1) ret=dfs(i,j);
        }
        return ret;
    }
};